package com.kadron.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import com.kadron.entity.OrderItem;

@AutoCreate
@BypassInterceptors
@Name(KOrderItemDAO.K_NAME)
public class KOrderItemDAO extends KDAO<OrderItem> {

	public static final String K_NAME = "orderItemDAO";
	
	@SuppressWarnings("unchecked")
	public List<OrderItem> getOrderItems(long orderId) {
		EntityManager em = getEntityManager();
		return em.createQuery("SELECT e FROM OrderItem e WHERE e.order.id=:orderId ORDER BY e.id ASC")
		.setParameter("orderId", orderId)
		.getResultList();
	}
	
	public Long getOrderedUserKadrons(long userId) {
		EntityManager em = getEntityManager();
		try {			
			return (Long) em.createQuery("SELECT SUM(e.kadrons*e.quantity) FROM OrderItem e WHERE e.order.user.id=:user_id GROUP BY e.order.user.id ")
				.setParameter("user_id", userId)
				.setMaxResults(1)
				.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
	public OrderItem find(long id) {
		EntityManager em = getEntityManager();
		try {			
			return (OrderItem) em.createQuery("SELECT e FROM OrderItem e WHERE e.id=:id")
			.setParameter("id", id)
			.setMaxResults(1)
			.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
}
